#include "FileProcessor.h"
#include "tinyxml2.h"
#include <iostream>
#include <regex>
using namespace std;
using namespace tinyxml2;

FileProcessor::FileProcessor(const vector<string> &xmls)
: _xmls(xmls){

}

FileProcessor::~FileProcessor(){

}

//xml解析
void FileProcessor::parseRss(){
    for(auto &xml: _xmls){
        XMLDocument doc;
        XMLError ret = doc.LoadFile(xml.c_str());
        if (ret != XML_SUCCESS) {
            cout << "Error loading XML file: " << doc.ErrorIDToName(ret) << "\n";
            return;
        }
        XMLElement *root = doc.RootElement();
        XMLElement *channel = root->FirstChildElement("channel");
        XMLElement *item = channel->FirstChildElement("item");
        while(item){
            RssItem rssItem;
            regex reg("<[^>]*>");
            XMLElement *itemTitle = item->FirstChildElement("title");
            rssItem.title = itemTitle->GetText();
            XMLElement *itemLink = item->FirstChildElement("link");
            rssItem.link = itemLink->GetText();
            XMLElement *itemContent = item->FirstChildElement("content");
            rssItem.content = itemContent->GetText();
            rssItem.content = regex_replace(rssItem.content, reg, "");
            if(rssItem.content.size() != 0){
                _items.push_back(rssItem);
            }
            item = item->NextSiblingElement();
        }
    }
}

//将解析后的数据输出到字符串数组
vector<string> FileProcessor::dump(){
    vector<string> _files;
    string doc;
    int docid = 1;
    for(size_t i = 0; i < _items.size(); i++){
        doc = "<doc><docid>" + to_string(docid) + "</docid>" +
              "<url>" + _items[i].link + "</url>" +
              "<title>" + _items[i].title + "</title>" + 
              "<content>" + _items[i].content + "</content></doc>"; 
        _files.push_back(doc);
        docid++;
    }
    return _files;
}

//打印
void FileProcessor::print()
{
    for(size_t i = 0; i < _items.size(); i++)
    {
        cout << _items[i].title << endl;
        cout << _items[i].link << endl;
        cout << _items[i].content << endl;
    }
}
